<?php
ini_set('error_reporting', E_ALL);
ini_set('log_errors', 'On');
require("../../class2.php");
require("library/api.php");

// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
}

$sql = new db;
$sql->db_Select($e107shop_db_name['gateways'], "*", "identifier='paypal'");

while ($row=$sql->db_Fetch()) {
    $PP_Paypal_Tmp = str_replace("https://", "", $row['field1']);
    $PP_Paypal_Url = str_replace("/cgi-bin/webscr", "", $PP_Paypal_Tmp);
}

// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ($PP_Paypal_Url, 80, $errno, $errstr, 30);
$ip = $_SERVER['REMOTE_ADDR'];

// assign posted variables to local variables
$item_name = $_POST['item_name'];
$business = $_POST['business'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$mc_gross = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$receiver_id = $_POST['receiver_id'];
$quantity = $_POST['quantity'];
$num_cart_items = $_POST['num_cart_items'];
$payment_date = $_POST['payment_date'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$payment_type = $_POST['payment_type'];
$payment_status = $_POST['payment_status'];
$payment_gross = $_POST['payment_gross'];
$payment_fee = $_POST['payment_fee'];
$settle_amount = $_POST['settle_amount'];
$memo = $_POST['memo'];
$payer_email = $_POST['payer_email'];
$txn_type = $_POST['txn_type'];
$payer_status = $_POST['payer_status'];
$address_street = $_POST['address_street'];
$address_city = $_POST['address_city'];
$address_state = $_POST['address_state'];
$address_zip = $_POST['address_zip'];
$address_country = $_POST['address_country'];
$address_status = $_POST['address_status'];
$item_number = $_POST['item_number'];
$tax = $_POST['tax'];
$option_name1 = $_POST['option_name1'];
$option_selection1 = $_POST['option_selection1'];
$option_name2 = $_POST['option_name2'];
$option_selection2 = $_POST['option_selection2'];
$for_auction = $_POST['for_auction'];
$invoice = $_POST['invoice'];
$custom = $_POST['custom'];
$notify_version = $_POST['notify_version'];
$verify_sign = $_POST['verify_sign'];
$payer_business_name = $_POST['payer_business_name'];
$payer_id =$_POST['payer_id'];
$mc_currency = $_POST['mc_currency'];
$mc_fee = $_POST['mc_fee'];
$exchange_rate = $_POST['exchange_rate'];
$settle_currency  = $_POST['settle_currency'];
$parent_txn_id  = $_POST['parent_txn_id'];

// subscription specific vars
$subscr_id = $_POST['subscr_id'];
$subscr_date = $_POST['subscr_date'];
$subscr_effective  = $_POST['subscr_effective'];
$period1 = $_POST['period1'];
$period2 = $_POST['period2'];
$period3 = $_POST['period3'];
$amount1 = $_POST['amount1'];
$amount2 = $_POST['amount2'];
$amount3 = $_POST['amount3'];
$mc_amount1 = $_POST['mc_amount1'];
$mc_amount2 = $_POST['mc_amount2'];
$mc_amount3 = $_POST['mcamount3'];
$recurring = $_POST['recurring'];
$reattempt = $_POST['reattempt'];
$retry_at = $_POST['retry_at'];
$recur_times = $_POST['recur_times'];
$username = $_POST['username'];
$password = $_POST['password'];

//auction specific vars
$for_auction = $_POST['for_auction'];
$auction_closing_date  = $_POST['auction_closing_date'];
$auction_multi_item  = $_POST['auction_multi_item'];
$auction_buyer_id  = $_POST['auction_buyer_id'];

//DB connect creds and email 
$notify_email = $shop_settings["order_email"]; //email address to which debug emails are sent to

if (!$fp) {
    error_log($req, 0);
} else {
    fputs ($fp, $header . $req);
    while (!feof($fp)) {
        $res = fgets ($fp, 1024);
        if (strcmp ($res, "VERIFIED") == 0) {

            $fecha = date("m")."/".date("d")."/".date("Y");
            $fecha = date("Y").date("m").date("d");

            //check if transaction ID has been processed before
            $nm = $sql->db_Count($e107shop_db_name['pp_payment_info'], "(*)", "WHERE txnid='".$txn_id."'");
            if ($nm == 0){
                //execute query
                $sql->db_Insert($e107shop_db_name['pp_payment_info'], "'".$first_name."', '".$last_name."', '"
                .$payer_email."', '".$address_street."', '".$address_city."', '".$address_state."', '"
                .$address_zip."', '".$memo."', '".$item_name."', '".$item_number."', '".$option_selection1."', '"
                .$option_name1."', '".$option_selection2."', '".$option_name2."', '".$quantity."', '"
                .$payment_date."', '".$payment_type."', '".$txn_id."', '".$mc_gross."', '".$mc_fee."', '"
                .$payment_status."', '".$pending_reason."', '".$txn_type."', '".$tax."', '".$mc_currency."', '"
                .$reason_code."', '".$custom."', '".$address_country."', '".$fecha."'") 
                or mail($notify_email, "pp_payment_info Query failed", mysql_error()."\n".mysql_errno());
                if ($payment_status=="Completed") {
                    e107shop_pay_order($invoice);
                } else {
                    mail($notify_email, "WACHTEN OP BETALING", "Order $invoice wacht nog steeds op betaling");
                }

                   // send an email in any case
                   mail($notify_email, "VERIFIED IPN", "$res\n $req\n $strQuery\n $struery\n  $strQuery2");
            } else {
                // send an email
                mail($notify_email, "VERIFIED DUPLICATED TRANSACTION", "$res\n $req \n $strQuery\n $struery\n  $strQuery2");
            }

        } else if (strcmp ($res, "INVALID") == 0) {

            // if the IPN POST was 'INVALID'...do this
            // log for manual investigation
            mail($notify_email, "INVALID IPN", "$res\n $req");
        }
    }
    fclose ($fp);
}
